<template>
	<wd-toast />
	<BpmComponent :processInstanceId="processInstanceId" @success="refreshDetail">
		<template #approval-info>
			<up-form labelPosition="left" labelWidth="80" v-if="Object.keys(formData).length > 0">
				<up-form-item v-for="field in formFields" :key="field.key" :label="field.label" borderBottom>
					<!-- 如果是附件 -->
					<view v-if="field.isDocument && formData[field.key]" class="file-actions">
						<template v-if="field.isArray">
							<view v-for="(item, idx) in formData[field.key]" :key="idx" class="file-item">
								<text class="file-link" @click="previewFile(item, formData[field.name]?.[idx])">
									{{ getFileName(formData[field.name][idx]) || '无' }}
								</text>
								<!-- <wd-icon name="delete-thin" size="16px" color="red" style="margin-left:8px"
							    @click="deleteFile(field.key)" /> -->
								<wd-icon v-if="field.key === `mainTextUrl`" name="upload" size="16px" color="#409eff"
									style="margin-left:6px" @click="() => reUploadFile(field.key)" />
							</view>
						</template>

						<!-- 如果不是数组 -->
						<template v-else>
							<text class="file-link" @click="previewFile(formData[field.key], formData[field.name])">
								{{ getFileName(formData[field.name]) || '无' }}
							</text>
							<!-- <wd-icon name="delete-thin" size="16px" color="red" style="margin-left:8px"
							@click="deleteFile(field.key)" /> -->
							<wd-icon v-if="field.key === `mainTextUrl`" name="upload" size="16px" color="#409eff"
								style="margin-left:6px" @click="() => reUploadFile(field.key)" />
						</template>
					</view>

					<!-- 普通字段 -->
					<text v-else>
						{{ field.format ? field.format(formData[field.key]) : formData[field.key] || '无' }}
					</text>
				</up-form-item>
			</up-form>
		</template>
	</BpmComponent>
	<wd-popup v-model="uploadDialogVisible" title="重新上传文件" custom-style="width: 80vw; max-width: 500px;">
		<view class="flex flex-direction-column flex-align-center p-3">
			<wd-form ref="formRef" labelWidth="120" :model="formData" :rules="formRules" class="w-full">
				<wd-cell title="重新上传文件" title-width="200px" />

				<!-- 上传组件居中 -->
				<view class="w-full flex flex-justify-center">
					<wd-upload :file-list="uploadFileList" :action="globalConfig.uploadUrl" :limit="1" accept="all"
						:show-upload-list="true" :header="headerObj"
						@success="(res: any) => handleMainTextUploadSuccess(res)" />
				</view>

				<!-- 确认按钮居中 -->
				<view class="flex flex-justify-center mt-3">
					<wd-button type="success" @click="confirmMainTextUpload" custom-class="custom-shadow"
						custom-style="width: 30vw; height: 28px;">
						确认
					</wd-button>
				</view>
			</wd-form>
		</view>
	</wd-popup>


</template>

<script setup lang="ts">
import { onLoad } from "@dcloudio/uni-app";
import { ref, unref, reactive, nextTick, getCurrentInstance } from 'vue'
import { DICT_TYPE, getDictLabel } from '@/utils/dict'
import { getAccessToken } from '@/utils/auth'
import BpmComponent from '@/components/processInstance/detail/index.vue'
import { getOutGoingPage, getOutGoingHistoryByYear, deleteOutGoing, createOutGoing, getOutGoing, deleteSendoutArticle } from '@/api/safety/outgoingsafety'
import { useMessage, useToast } from 'wot-design-uni'
import { getFileName, parseArrayField,previewFile } from '@/utils/fileUtils'

const message = useMessage()
const toast = useToast()

const globalConfig = (getApp() as any).globalData.config;
const headerObj = ref(
	{
		Authorization: 'Bearer ' + getAccessToken()
	}
)
const processInstanceId = ref(null)// 流程实例的编号
const detailId = ref(null)
const formData = ref<any>({} as any)
const formFields = [
	// {
	// 	label: '类型', key: 'type', format: (val: any) => {
	// 		return getDictLabel(DICT_TYPE.OA_OUT_TYPE, val)
	// 	}
	// },
	{ label: '标题', key: 'title' },
	{ label: '主送', key: 'mainRecipient' },
	{ label: '抄送', key: 'ccSend' },
	{ label: '发文字号', key: 'documentNumber' },
	{ label: '校对人', key: 'proofreader' },
	{ label: '印份数', key: 'totalPrinted' },
	{ label: '正文', key: 'mainTextUrl', isDocument: true, name: 'mainTextName' },
	{ label: '附件', key: 'eids', isDocument: true, name: 'ename', isArray: true },


]

/*重新上传文件*/

const uploadDialogVisible = ref(false)
const uploadFileList = ref<any[]>([])
const currentUploadFieldKey = ref('')
/** 点击重新上传图标，打开弹窗 */
const reUploadFile = (key: string) => {
	console.log('点击了');

	currentUploadFieldKey.value = key
	uploadFileList.value = [] // 可选：初始化清空
	uploadDialogVisible.value = true
}

/** 正文上传成功回调 */
const handleMainTextUploadSuccess = (response: any) => {
	console.log('response', response);


	// 更新临时数据，等待用户确认
	const name = response.file.name
	const newMainTextName = name.replace(/\.pdf$/, '') as any
	const newMainTextUrl = JSON.parse(response.file.response).data
	console.log('newMainTextName', newMainTextName);
	console.log('newMainTextUrl', newMainTextUrl);

	// 暂存新上传的文件信息
	uploadFileList.value = [{
		name: newMainTextName,
		url: newMainTextUrl,
		status: 'success',
		response: { data: newMainTextUrl }
	}]

	// 提示成功
	toast.success('正文上传成功');
}
/** 确认正文上传 */
const confirmMainTextUpload = async () => {
	if (uploadFileList.value.length === 0) {
		toast.error('请先上传文件')
		return
	}

	try {
		// uploadLoading.value = true

		const fileInfo = uploadFileList.value[0]
		const newMainTextName = fileInfo.name
		const newMainTextUrl = fileInfo.response.data

		// 调用deleteSendoutArticle接口更新正文信息
		const updateData = {
			id: formData.value.id,
			mainTextName: newMainTextName,
			mainTextUrl: newMainTextUrl
		}

		await deleteSendoutArticle(updateData)

		// 更新本地数据
		formData.value.mainTextName = newMainTextName
		formData.value.mainTextUrl = newMainTextUrl

		// 关闭对话框
		uploadDialogVisible.value = false

		// 提示成功
		toast.success('正文重新上传成功')
	} catch (error) {
		console.error('更新正文失败:', error)
		toast.error('更新正文失败')
	} finally {
		// uploadLoading.value = false
	}
}
onLoad(async (options) => {
	processInstanceId.value = options?.processInstanceId
	detailId.value = options?.id
	/** 获得详情 */
	getDetailById()
})
const refreshDetail = () => {
	console.log('父组件收到刷新事件，重新加载数据')
	getDetailById() // 调用父组件自己的获取详情方法
}
/** 获取页面详情 */
const getDetailById = async () => {
	try {
		const data = await getOutGoing(Number(detailId.value))
		formData.value = data
		console.log('data', data);
		formData.value.eids = parseArrayField(data.eids);
		formData.value.ename = parseArrayField(data.ename);
		// formData.value.mainTextUrl = parseFirst(data.mainTextUrl);
		// formData.value.mainTextName = parseFirst(data.mainTextName);
		console.log('formData.value', formData.value);


	} catch (error) {
		console.log('加载数据失败')
	}
}
defineExpose({ reUploadFile })
</script>

<style>
.custom-shadow {
	width: 90%;
	font-size: 18px;
}

/* 样式 */
/* 新增文件链接样式 */
.file-link {
	margin-right: 20rpx;
	display: inline-block;
	/* 让宽度生效 */
	max-width: 240px;
	/* 你可以改为你想要的宽度 */
	overflow: hidden;
	/* 超出部分隐藏 */
	white-space: nowrap;
	/* 不换行 */
	text-overflow: ellipsis;
	/* 超出显示省略号 */
	color: #007AFF;
	text-decoration: underline;
	cursor: pointer;

}

.uv-node {
	height: 34rpx;
	width: 34rpx;
	border-radius: 50%;
	background-color: #ddd;
	display: flex;
	align-items: center;
	justify-content: center;
	color: #fff;
	flex-shrink: 0;
	z-index: -1;
}

.audit-node {
	margin: 5px 0;
}
</style>